package com.xcjh.module_ad

import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import com.google.android.gms.ads.MobileAds
import com.xcjh.base_lib.App
import com.xcjh.base_lib.utils.loge
import com.xcjh.module_ad.manager.AppOpenAdManager

private const val AD_UNIT_ID = "ca-app-pub-3940256099942544/3419835294"
private const val LOG_TAG = "MyApplication"

/** 在 Activity 更改状态时初始化、加载和显示广告的应用程序类 */
class MyApplication : App(), Application.ActivityLifecycleCallbacks, LifecycleObserver {

    private lateinit var appOpenAdManager: AppOpenAdManager
    private var currentActivity: Activity? = null

    private var number:Int=0
    override fun onCreate() {
        super.onCreate()
        registerActivityLifecycleCallbacks(this)
        MobileAds.initialize(this) {}
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
        appOpenAdManager = AppOpenAdManager()
    }

    /** LifecycleObserver 方法，当应用移至前台时显示应用打开广告。 */
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onMoveToForeground() {
        // 当应用移至前台时显示广告（如果有）。
        if (number%3==0){
            currentActivity?.let {
                appOpenAdManager.showAdIfAvailable(it)
            }
        }
        number++
    }

    /** ActivityLifecycleCallback methods. */
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}

    override fun onActivityStarted(activity: Activity) {
        // 广告activity在展示广告时启动，该activity可以是来自 Google SDK 的 AdActivity 类，也可以是第三方中介合作伙伴实施的另一个活动类。仅在广告未显示时更新 currentActivity 将确保它不是广告活动，而是显示广告的活动。
        if (!appOpenAdManager.isShowingAd) {
            currentActivity = activity
        }
    }

    override fun onActivityResumed(activity: Activity) {
        "onActivityResumed".loge(activity.componentName.toString()+"==="+activity.localClassName)
    }

    override fun onActivityPaused(activity: Activity) {
        "onActivityPaused".loge(activity.componentName.toString()+"==="+activity.localClassName)
    }

    override fun onActivityStopped(activity: Activity) {}

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

    override fun onActivityDestroyed(activity: Activity) {
        "onActivityDestroyed".loge("===")
    }

    /**
     * 显示开屏广告。
     * @param activity 显示应用程序打开广告的活动
     * @param action 应用程序打开广告完成时要通知的侦听器
     */
    fun showAdIfAvailable(activity: Activity, action: () -> Unit = {}) {
        // We wrap the showAdIfAvailable to enforce that other classes only interact with MyApplication
        // class.
        appOpenAdManager.showAdIfAvailable(activity, action)
    }


}